package com.dhcc.bpm.modules.sandbox.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.common.utils.DateUtils;
import com.dhcc.bpm.common.utils.FormatUtils;
import com.dhcc.bpm.common.utils.StringUtils;
import com.dhcc.bpm.modules.api.entity.Product;
import com.dhcc.bpm.modules.api.service.IApiService;
import com.dhcc.bpm.modules.api.service.IProductService;
import com.dhcc.bpm.modules.api.vo.ApiVO;
import com.dhcc.bpm.modules.log.entity.GatewayLog;
import com.dhcc.bpm.modules.log.service.IGatewayLogDayService;
import com.dhcc.bpm.modules.log.service.IGatewayLogMinuteService;
import com.dhcc.bpm.modules.log.service.IGatewayLogService;
import com.dhcc.bpm.modules.log.vo.GatewayLogDayVO;
import com.dhcc.bpm.modules.log.vo.GatewayLogMinuteVO;
import com.dhcc.bpm.modules.log.vo.TradeAppVo;
import com.dhcc.bpm.modules.orga.service.IAppApiService;
import com.dhcc.bpm.modules.orga.service.IAppService;
import com.dhcc.bpm.modules.orga.vo.AppApiVO;
import com.dhcc.bpm.modules.sandbox.entity.SandboxCase;
import com.dhcc.bpm.modules.sandbox.service.ISandboxApiService;
import com.dhcc.bpm.modules.sandbox.service.ISandboxCaseDictService;
import com.dhcc.bpm.modules.sandbox.service.ISandboxCaseService;
import com.dhcc.bpm.modules.sandbox.vo.SandboxApiVO;
import com.dhcc.bpm.modules.sandbox.vo.SandboxCaseDictVO;
import com.dhcc.bpm.modules.sandbox.vo.SandboxCaseVO;
import com.dhcc.bpm.modules.system.service.ISerialNumberService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.*;
/**
 * @ClassName SandboxCaseController
 * @Description 沙箱实例表 控制器
 * @Author sjm
 * @Date 2020/2/21 0021 15:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 **/
@RestController
@AllArgsConstructor
@RequestMapping("bpm-sandbox/sandboxcase")
@Api(value = "沙箱实例表", tags = "沙箱实例表接口")
public class SandboxCaseController extends BladeController {
	private final static Logger log = LoggerFactory.getLogger(SandboxCaseController.class);
	private ISandboxCaseService sandboxCaseService;
	private ISerialNumberService serialNumberService;
	private ISandboxCaseDictService sandboxCaseDictService;
	private ISandboxApiService sandboxApiService;
	private IAppApiService appApiService;
	private IApiService apiService;
	private IGatewayLogService gatewayLogService;
	private IAppService appService;
	private IProductService productService;
	private IGatewayLogDayService gatewayLogDayService;
	private IGatewayLogMinuteService gatewayLogMinuteService;

	/**
	 * @param sandboxCase
	 * @return org.springblade.core.tool.api.R<com.dhcc.bpm.modules.sandbox.entity.SandboxCase>
	 * @Description 详情
	 * @Author sjm
	 * @Date 21:32 2020/2/21 0021
	 **/
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入sandboxCase")
	@ApiLog("沙箱实例详情")
	@Log(title = "沙箱实例详情", businessType = BusinessType.SELECT)
	public R<SandboxCase> detail(SandboxCase sandboxCase) {
		SandboxCase detail = sandboxCaseService.getById(sandboxCase.getId());
		return R.data(detail);
	}

	/**
	 * @param sandboxCase
	 * @param query
	 * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.sandbox.entity.SandboxCase>>
	 * @Description 分页 沙箱实例表
	 * @Author sjm
	 * @Date 21:32 2020/2/21 0021
	 **/
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入sandboxCase")
	@ApiLog("沙箱实例表")
	@Log(title = "沙箱实例表", businessType = BusinessType.SELECT)
	public R<IPage<SandboxCase>> list(@ApiIgnore @RequestParam Map<String, Object> sandboxCase, Query query) {
		IPage<SandboxCase> pages = sandboxCaseService.page(Condition.getPage(query), Condition.getQueryWrapper(sandboxCase, SandboxCase.class));
		return R.data(pages);
	}

	/**
	 * @param sandboxCase
	 * @param query
	 * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.sandbox.vo.SandboxCaseVO>>
	 * @Description 自定义分页 沙箱实例表
	 * @Author sjm
	 * @Date 21:32 2020/2/21 0021
	 **/
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入sandboxCase")
	@ApiLog("分页查询沙箱实例表")
	@Log(title = "沙箱实例表", businessType = BusinessType.SELECT)
	public R<IPage<SandboxCaseVO>> page(SandboxCaseVO sandboxCase, Query query) {
		IPage<SandboxCaseVO> pages = sandboxCaseService.selectSandboxCasePage(Condition.getPage(query), sandboxCase);
		return R.data(pages);
	}

	/**
	 * @param sandboxCase
	 * @return org.springblade.core.tool.api.R
	 * @Description 新增 沙箱实例表
	 * @Author sjm
	 * @Date 21:32 2020/2/21 0021
	 **/
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入sandboxCase")
	@ApiLog("沙箱实例新增")
	@Log(title = "沙箱实例新增", businessType = BusinessType.INSERT)
	public R save(@Valid @RequestBody SandboxCase sandboxCase) {
		return R.status(sandboxCaseService.save(sandboxCase));
	}

	/**
	 * @param sandboxCase
	 * @return org.springblade.core.tool.api.R
	 * @Description 修改 沙箱实例表
	 * @Author sjm
	 * @Date 21:32 2020/2/21 0021
	 **/
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入sandboxCase")
	@ApiLog("沙箱实例修改")
	@Log(title = "沙箱实例修改", businessType = BusinessType.UPDATE)
	public R update(@Valid @RequestBody SandboxCase sandboxCase) {
		return R.status(sandboxCaseService.updateById(sandboxCase));
	}

	/**
	 * @param sandboxCase
	 * @return org.springblade.core.tool.api.R
	 * @Description 新增或修改 沙箱实例表
	 * @Author sjm
	 * @Date 21:32 2020/2/21 0021
	 **/
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入sandboxCase")
	@ApiLog("沙箱实例新增修改")
	@Log(title = "沙箱实例新增修改", businessType = BusinessType.UPDATE)
	@Transactional(rollbackFor = Exception.class)
	public R submit(@Valid @RequestBody SandboxCase sandboxCase) {
		try {
			if (sandboxCase.getId() == null) {
				String date = serialNumberService.generateSerialNumberByModelCode("sandbox_case_date");
				String num = serialNumberService.generateSerialNumberByModelCode("sandbox_case_num");
				String code = date.substring(0, date.length() - 1) + num;
				sandboxCase.setCaseCode(code);
			}
			sandboxCaseService.saveOrUpdate(sandboxCase);
			List<AppApiVO> list = appApiService.findApiListByAppId(sandboxCase.getOpcAppId());
			for (AppApiVO appApiVO : list) {
				SandboxApiVO sandboxApi = sandboxApiService.selectSandboxApiList(sandboxCase.getId(), appApiVO.getOpcAppId());
				if (sandboxApi != null) {
					sandboxApi.setApiId(appApiVO.getOpcApiId());
				} else {
					sandboxApi = new SandboxApiVO();
					sandboxApi.setApiId(appApiVO.getOpcApiId());
					sandboxApi.setCaseId(sandboxCase.getId());
				}
				sandboxApiService.saveOrUpdate(sandboxApi);
			}
			return R.status(true);
		} catch (Exception e) {
			log.error("沙箱案例执行异常：{}", e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.status(false);
		}
	}


	/**
	 * @param ids
	 * @return org.springblade.core.tool.api.R
	 * @Description 删除 沙箱实例表
	 * @Author sjm
	 * @Date 21:33 2020/2/21 0021
	 **/
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	@ApiLog("沙箱实例删除")
	@Log(title = "沙箱实例删除", businessType = BusinessType.DELETE)
	@Transactional(rollbackFor = Exception.class)
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> list = Func.toLongList(ids);
		for (Long caseId : list) {
			List<SandboxCaseDictVO> dictLis = sandboxCaseDictService.selectSandboxCase(caseId);
			for (SandboxCaseDictVO sandboxCaseDictVO : dictLis) {
				sandboxCaseDictService.removeById(sandboxCaseDictVO.getId());
			}
		}
		return R.status(sandboxCaseService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * @param appCode
	 * @return org.springblade.core.tool.api.R
	 * @Description 查询应用下的接口成功率
	 * @Author sjm
	 * @Date 21:33 2020/2/21 0021
	 **/
	@PostMapping("/selectApiSuccessRate")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "查询应用下的接口成功率", notes = "传入ids")
	@ApiLog("查询应用下的接口统计")
	@Log(title = "查询应用下的接口统计", businessType = BusinessType.SELECT)
	public R selectApiSuccessRate(@ApiParam(value = "主键集合", required = true) @RequestParam String appCode, @ApiParam(value = "环境标识", required = true) @RequestParam String env) {
		GatewayLog gatewayLog = new GatewayLog();
		gatewayLog.setEnvType(env);
		gatewayLog.setOpcAppCode(appCode);
		//成功数
		int successCount = gatewayLogService.selectApiSuccessCount(gatewayLog);
		//执行总数
		QueryWrapper<GatewayLog> queryWrapper = Condition.getQueryWrapper(gatewayLog);
		int num = Math.toIntExact(gatewayLogService.count(queryWrapper));
		// 求成功率
		String successRate = "0.00";
		//格式化小数
		DecimalFormat df = new DecimalFormat("0.00");
		if (num == 0) {
			double value = 0;
			//返回的是String类型
			successRate = FormatUtils.doubleFormat(value);
		} else {
			double value = (double) successCount / num * 100;
			//返回的是String类型
			successRate = FormatUtils.doubleFormat(value);
		}
		return R.data(successRate);
	}

	/**
	 * @param appCode
	 * @return org.springblade.core.tool.api.R<java.util.HashMap < java.lang.String, java.lang.Integer>>
	 * @Description 统计应用异常占比
	 * @Author sjm
	 * @Date 21:33 2020/2/21 0021
	 **/
	@PostMapping("/selectAbnormal")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "统计应用异常占比", notes = "传入app")
	@ApiLog("查询统计应用异常占比")
	@Log(title = "查询统计应用异常占比", businessType = BusinessType.SELECT)
	public R<HashMap<String, Integer>> selectAbnormal(@ApiParam(value = "主键集合", required = true) @RequestParam String appCode, @ApiParam(value = "环境标识", required = true) @RequestParam String env) {
		GatewayLog gatewayLog = new GatewayLog();
		gatewayLog.setOpcAppCode(appCode);
		gatewayLog.setEnvType(env);

		int gateNum = gatewayLogService.selectGateCount(gatewayLog);
		int busNum = gatewayLogService.selectBusCount(gatewayLog);
		int infoNum = gatewayLogService.selectInfoCount(gatewayLog);
		int gateNums = (gateNum == 0) ? 1 : gateNum;
		int busNums = (busNum == 0) ? 1 : busNum;
		int infoNums = (infoNum == 0) ? 1 : infoNum;
		//异常总数
		int sumCount = gateNums + busNums + infoNums;
		List<String> typeList = new ArrayList<>();
		typeList.add("gateExp");
		typeList.add("busExp");
		typeList.add("infoExp");
		HashMap<String, Integer> hashMap = new HashMap();
		typeList.forEach(type -> {
			int count = 0;
			if ("gateExp".equals(type)) {
				count = gateNums;
			} else if ("busExp".equals(type)) {
				count = busNums;
			} else if ("infoExp".equals(type)) {
				count = infoNums;
			}
			hashMap.put(type, count);
		});
		hashMap.put("total", sumCount);
		return R.data(hashMap);
	}

	/**
	 * @param apiVO
	 * @return org.springblade.core.tool.api.R<java.util.HashMap < java.lang.String, java.lang.Integer>>
	 * @Description 统计机构异常占比
	 * @Author sjm
	 * @Date 21:33 2020/2/21 0021
	 **/
	@PostMapping("/selectOrgaAbnormal")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "统计应用异常占比", notes = "传入app")
	@ApiLog("查询统计应用异常占比")
	@Log(title = "查询统计应用异常占比", businessType = BusinessType.SELECT)
	public R<HashMap<String, Integer>> selectOrgaAbnormal(ApiVO apiVO, BladeUser bladeUser) {
		GatewayLog gatewayLog = new GatewayLog();
		gatewayLog.setEnvType(apiVO.getEnv());
		int gateNum = 0, busNum = 0, infoNum = 0;

		if (StringUtils.isNotEmpty(apiVO.getKind()) && "product".equals(apiVO.getKind())) { // 应用产品
			IPage<ApiVO> req = new Page<ApiVO>();
			req.setCurrent(1);
			req.setSize(99999999); // 不分页，查所有
			IPage<ApiVO> page = apiService.selectProductApiList(req, apiVO);
			if (page.getRecords() != null && page.getRecords().size() > 0) {
				for (ApiVO vo : page.getRecords()) {
					gatewayLog.setOpcApiCode(vo.getApiCode());
					gateNum += gatewayLogService.gateCount(gatewayLog);
					busNum += gatewayLogService.busCount(gatewayLog);
					infoNum += gatewayLogService.infoCount(gatewayLog);
				}
			}
		} else if (StringUtils.isNotEmpty(apiVO.getKind()) && "sys".equals(apiVO.getKind())) { // 系统
			// 系统下产品集合
			List<Product> sysProlist = productService.syslist(apiVO.getSysId());
			if (sysProlist != null && sysProlist.size() > 0) {
				// 产品下API统计
				for (Product proVO : sysProlist) {
					IPage<ApiVO> req = new Page<ApiVO>();
					req.setCurrent(1);
					req.setSize(99999999); // 不分页，查所有
					ApiVO apiVO1 = new ApiVO();
					apiVO1.setOpcProductId(proVO.getId());
					IPage<ApiVO> page = apiService.selectProductApiList(req, apiVO1);
					if (page.getRecords() != null && page.getRecords().size() > 0) {
						for (ApiVO vo : page.getRecords()) {
							if (vo != null && vo.getApiCode() != null) {
								gatewayLog.setOpcApiCode(vo.getApiCode());
							}
							gateNum += gatewayLogService.gateCount(gatewayLog);
							busNum += gatewayLogService.busCount(gatewayLog);
							infoNum += gatewayLogService.infoCount(gatewayLog);
						}
					}
				}
			}
		} else { // 机构
			gatewayLog.setOpcOrgaCode(apiVO.getOrgaCard());
			gateNum = gatewayLogService.gateCount(gatewayLog);
			busNum = gatewayLogService.busCount(gatewayLog);
			infoNum = gatewayLogService.infoCount(gatewayLog);

		}
		//异常数是0是 赋值默认值
		gateNum = (gateNum == 0) ? 1 : gateNum;
		busNum = (busNum == 0) ? 1 : busNum;
		infoNum = (infoNum == 0) ? 1 : infoNum;

		//异常总数
		int sumCount = gateNum + busNum + infoNum;
		List<String> typeList = new ArrayList<>();
		typeList.add("gateExp");
		typeList.add("busExp");
		typeList.add("infoExp");
		HashMap<String, Integer> hashMap = new HashMap();

		for (String type : typeList) {
			int count = 0;
			if ("gateExp".equals(type)) {
				count = gateNum;
			} else if ("busExp".equals(type)) {
				count = busNum;
			} else if ("infoExp".equals(type)) {
				count = infoNum;
			}
			hashMap.put(type, count);
		}
		hashMap.put("total", sumCount);
		return R.data(hashMap);


	}


	/**
	 * @param appCode
	 * @return org.springblade.core.tool.api.R<java.util.HashMap < java.lang.String, java.lang.Integer>>
	 * @Description 查询api的统计数量
	 * @Author sjm
	 * @Date 21:33 2020/2/21 0021
	 **/
	@PostMapping("/selectApiCount")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "查询应用下的接口成功次数", notes = "传入ids")
	@ApiLog("查询api的统计数量")
	@Log(title = "查询api的统计数量", businessType = BusinessType.SELECT)
	public R<HashMap<String, Integer>> selectApiCount(@ApiParam(value = "主键集合", required = true) @RequestParam String appCode, @ApiParam(value = "环境标识", required = true) @RequestParam String env) {
		HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
		//服务总数
		int apiCount = apiService.selectApiCountById(appCode);
		//执行次数
		GatewayLog gatewayLog = new GatewayLog();
		gatewayLog.setOpcAppCode(appCode);
		gatewayLog.setEnvType(env); // 环境标志 0-生产环境  1-沙箱
		QueryWrapper<GatewayLog> queryWrapper = Condition.getQueryWrapper(gatewayLog);
		int callCount = Math.toIntExact(gatewayLogService.count(queryWrapper));
		//成功数
		int successCount = gatewayLogService.selectApiSuccessCount(gatewayLog);
		//失败数
		int failCount = gatewayLogService.selectApiFailCount(gatewayLog);
		//网关异常数
		int gateCount = gatewayLogService.selectGateCount(gatewayLog);
		//业务异常数
		int busCount = gatewayLogService.selectBusCount(gatewayLog);
		//通讯异常
		int infoCount = gatewayLogService.selectInfoCount(gatewayLog);
		hashMap.put("apiCount", apiCount);
		hashMap.put("callCount", callCount);
		hashMap.put("successCount", successCount);
		hashMap.put("failCount", failCount);
		hashMap.put("gateCount", gateCount);
		hashMap.put("busCount", busCount);
		hashMap.put("infoCount", infoCount);
		return R.data(hashMap);
	}

	/**
	 * @param apiVO
	 * @return org.springblade.core.tool.api.R<java.util.HashMap < java.lang.String, java.lang.Integer>>
	 * @Description 机构下执行结果8块数据的统计
	 * @Author Mdd
	 * @Date 2020/3/7 18:32
	 **/
	@PostMapping("/selectOrgaApiCount")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "机构下执行结果8块数据的统计", notes = "传入ids")
	@ApiLog("机构下执行结果8块数据的统计")
	@Log(title = "机构下执行结果8块数据的统计", businessType = BusinessType.SELECT)
	public R<HashMap<String, Integer>> selectOrgaApiCount(ApiVO apiVO, BladeUser bladeUser) {
		HashMap<String, Integer> hashMap = new HashMap();
		int callCount = 0, successCount = 0, failCount = 0, gateCount = 0, busCount = 0, infoCount = 0;
		GatewayLog gatewayLog = new GatewayLog();
		gatewayLog.setEnvType(apiVO.getEnv());

		if (StringUtils.isNotEmpty(apiVO.getKind()) && "product".equals(apiVO.getKind())) { // 应用产品
			IPage<ApiVO> req = new Page<ApiVO>();
			req.setCurrent(1);
			req.setSize(99999999); // 不分页，查所有
			IPage<ApiVO> page = apiService.selectProductApiList(req, apiVO);
			if (page.getRecords() != null && page.getRecords().size() > 0) {
				for (ApiVO vo : page.getRecords()) {
					gatewayLog.setOpcApiCode(vo.getApiCode());

					QueryWrapper<GatewayLog> queryWrapper = Condition.getQueryWrapper(gatewayLog);
					queryWrapper = Condition.getQueryWrapper(gatewayLog);
					//执行次数
					callCount += gatewayLogService.count(queryWrapper);
					//成功数
					successCount += gatewayLogService.selectSuccessCount(gatewayLog);
					//失败数
					failCount += gatewayLogService.selectFailCount(gatewayLog);
					//网关异常数
					gateCount += gatewayLogService.gateCount(gatewayLog);
					//业务异常数
					busCount += gatewayLogService.busCount(gatewayLog);
					//通讯异常
					infoCount += gatewayLogService.infoCount(gatewayLog);
				}
			}
		} else if (StringUtils.isNotEmpty(apiVO.getKind()) && "sys".equals(apiVO.getKind())) { // 系统
			// 某一系统下产品集合
			List<Product> sysProlist = productService.syslist(apiVO.getSysId());

			if (sysProlist != null && sysProlist.size() > 0) {
				// 产品集合下API统计
				for (Product proVO : sysProlist) { // 某一产品
					IPage<ApiVO> req = new Page<ApiVO>();
					req.setCurrent(1);
					req.setSize(99999999); // 不分页，查所有
					apiVO.setOpcProductId(proVO.getId());
					// 某一产品下所有API
					IPage<ApiVO> page = apiService.selectProductApiList(req, apiVO);
					if (page != null && page.getRecords() != null && page.getRecords().size() > 0) {
						for (ApiVO vo : page.getRecords()) { // 某一API
							if (vo != null && vo.getApiCode() != null) {
								gatewayLog.setOpcApiCode(vo.getApiCode());
							}
							QueryWrapper<GatewayLog> queryWrapper = Condition.getQueryWrapper(gatewayLog);

							queryWrapper = Condition.getQueryWrapper(gatewayLog);
							//执行次数
							callCount += gatewayLogService.count(queryWrapper);
							//成功数
							successCount += gatewayLogService.selectSuccessCount(gatewayLog);
							//失败数
							failCount += gatewayLogService.selectFailCount(gatewayLog);
							//网关异常数
							gateCount += gatewayLogService.gateCount(gatewayLog);
							//业务异常数
							busCount += gatewayLogService.busCount(gatewayLog);
							//通讯异常
							infoCount += gatewayLogService.infoCount(gatewayLog);
						}
					}
				}
			}

		} else { // 机构
			gatewayLog.setOpcOrgaCode(apiVO.getOrgaCard());
			QueryWrapper<GatewayLog> queryWrapper = Condition.getQueryWrapper(gatewayLog);
			queryWrapper = Condition.getQueryWrapper(gatewayLog);
			//执行次数
			callCount += gatewayLogService.count(queryWrapper);
			//成功数
			successCount = gatewayLogService.selectSuccessCount(gatewayLog);
			//失败数
			failCount = gatewayLogService.selectFailCount(gatewayLog);
			//网关异常数
			gateCount = gatewayLogService.gateCount(gatewayLog);
			//业务异常数
			busCount = gatewayLogService.busCount(gatewayLog);
			//通讯异常
			infoCount = gatewayLogService.infoCount(gatewayLog);
		}
		hashMap.put("callCount", callCount);
		hashMap.put("successCount", successCount);
		hashMap.put("failCount", failCount);
		hashMap.put("gateCount", gateCount);
		hashMap.put("busCount", busCount);
		hashMap.put("infoCount", infoCount);
		return R.data(hashMap);
	}

	/**
	 * @param apiVO
	 * @return org.springblade.core.tool.api.R
	 * @Description 查询成功率
	 * @Author sjm
	 * @Date 21:33 2020/2/21 0021
	 **/
	@PostMapping("/selectSuccessRate")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "查询成功率", notes = "传入ids")
	@ApiLog("查询成功率")
	@Log(title = "查询成功率", businessType = BusinessType.SELECT)
	public R selectSuccessRate(ApiVO apiVO, BladeUser bladeUser) {
		GatewayLog gatewayLog = new GatewayLog();
		gatewayLog.setEnvType(apiVO.getEnv());
		//格式化小数
		DecimalFormat df = new DecimalFormat("0.00");
		int num = 0;
		int successCount = 0;
		QueryWrapper<GatewayLog> queryWrapper = null;
		if (StringUtils.isNotEmpty(apiVO.getKind()) && "product".equals(apiVO.getKind())) { // 应用产品
			IPage<ApiVO> req = new Page<ApiVO>();
			req.setCurrent(1);
			req.setSize(99999999); // 不分页，查所有
			IPage<ApiVO> page = apiService.selectProductApiList(req, apiVO);
			if (page.getRecords() != null && page.getRecords().size() > 0) {
				for (ApiVO vo : page.getRecords()) {
					gatewayLog.setOpcApiCode(vo.getApiCode());
					queryWrapper = Condition.getQueryWrapper(gatewayLog);
					//执行总数
					num += gatewayLogService.count(queryWrapper);
					//成功数
					successCount += gatewayLogService.selectSuccessCount(gatewayLog);
				}
			}
		} else if (StringUtils.isNotEmpty(apiVO.getKind()) && "sys".equals(apiVO.getKind())) { // 系统
			// 某一系统下产品集合
			List<Product> sysProlist = productService.syslist(apiVO.getSysId());

			if (sysProlist != null && sysProlist.size() > 0) {
				// 产品集合下API统计
				for (Product proVO : sysProlist) { // 某一产品
					IPage<ApiVO> req = new Page<ApiVO>();
					req.setCurrent(1);
					req.setSize(99999999); // 不分页，查所有
					apiVO.setOpcProductId(proVO.getId());
					// 某一产品下所有API
					IPage<ApiVO> page = apiService.selectProductApiList(req, apiVO);
					if (page != null && page.getRecords() != null && page.getRecords().size() > 0) {
						for (ApiVO vo : page.getRecords()) { // 某一API
							if (vo != null && vo.getApiCode() != null) {
								gatewayLog.setOpcApiCode(vo.getApiCode());
							}
							queryWrapper = Condition.getQueryWrapper(gatewayLog);
							//执行总数
							num += gatewayLogService.count(queryWrapper);
							//成功数
							successCount += gatewayLogService.selectSuccessCount(gatewayLog);
						}
					}
				}
			}

		} else { // 机构
			gatewayLog.setOpcOrgaCode(apiVO.getOrgaCard());
			queryWrapper = Condition.getQueryWrapper(gatewayLog);
			//执行总数
			num = Math.toIntExact(gatewayLogService.count(queryWrapper));
			//成功数
			successCount = gatewayLogService.selectSuccessCount(gatewayLog);
		}
		// 求成功率
		String successRate = "0.00";
		if (num == 0) {
			double value = 0;
			//返回的是String类型
			successRate = FormatUtils.doubleFormat(value);
		} else {
			double value = (double) successCount / num * 100;
			//返回的是String类型
			successRate = FormatUtils.doubleFormat(value);
		}
		return R.data(successRate);
	}

	@PostMapping("/exportData")
	public R exportData(ApiVO api, Query query, String appCode, String env, String type) throws ParseException {

		IPage<ApiVO> pages = apiService.getApiListByCaseId(Condition.getPage(query), api);

		HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
		//服务总数
		int apiCount = apiService.selectApiCountById(appCode);
		//执行次数
		GatewayLog gatewayLog = new GatewayLog();
		gatewayLog.setOpcAppCode(appCode);
		gatewayLog.setEnvType(env); // 环境标志 0-生产环境  1-沙箱
		QueryWrapper<GatewayLog> queryWrapper = Condition.getQueryWrapper(gatewayLog);
		int callCount = Math.toIntExact(gatewayLogService.count(queryWrapper));
		//成功数
		int successCount = gatewayLogService.selectApiSuccessCount(gatewayLog);
		//失败数
		int failCount = gatewayLogService.selectApiFailCount(gatewayLog);
		//网关异常数
		int gateCount = gatewayLogService.selectGateCount(gatewayLog);
		//业务异常数
		int busCount = gatewayLogService.selectBusCount(gatewayLog);
		//通讯异常
		int infoCount = gatewayLogService.selectInfoCount(gatewayLog);
		hashMap.put("apiCount", apiCount);
		hashMap.put("callCount", callCount);
		hashMap.put("successCount", successCount);
		hashMap.put("failCount", failCount);
		hashMap.put("gateCount", gateCount);
		hashMap.put("busCount", busCount);
		hashMap.put("infoCount", infoCount);


		//执行总数
		int num = Math.toIntExact(gatewayLogService.count(queryWrapper));
		// 求成功率
		String successRate = "0.00";
		//格式化小数
		DecimalFormat df = new DecimalFormat("0.00");
		if (num == 0) {
			double value = 0;
			//返回的是String类型
			successRate = FormatUtils.doubleFormat(value);
		} else {
			double value = (double) successCount / num * 100;
			//返回的是String类型
			successRate = FormatUtils.doubleFormat(value);
		}

//		成功率
//		successRate

		//统计
		String nowDate = DateUtils.dateTime();
		List<TradeAppVo> appList = new ArrayList<TradeAppVo>();
		List<TradeAppVo> dataList = new ArrayList<>();
		GatewayLogDayVO gatewayLogDayVO = new GatewayLogDayVO();
		gatewayLogDayVO.setEnv(env);
		String flag = "";
		switch (type) {
			case "day":
				GatewayLogMinuteVO gatewayLogMinuteVO = new GatewayLogMinuteVO();
				gatewayLogMinuteVO.setRequestDate(nowDate);
				gatewayLogMinuteVO.setOpcAppCode(appCode);
				gatewayLogMinuteVO.setEnv(env);
				appList = gatewayLogMinuteService.selectApiCountByDay(gatewayLogMinuteVO);
				Map<Integer, Integer> mapDay = new LinkedHashMap<Integer, Integer>();
				for (int i = 0; i < 12; i++) {
					mapDay.put(i * 2, 0);
				}

				if (appList != null && appList.size() > 0) {
					for (TradeAppVo tradeAppVo : appList) {
						int requestNum = tradeAppVo.getRequestNum();
						int hour = (int) Math.floor(Integer.valueOf(tradeAppVo.getRequestDate()) / 2);
						mapDay.put(hour * 2, mapDay.get(hour * 2) + requestNum);
					}
				}

				for (Integer hour : mapDay.keySet()) {
					TradeAppVo appVo = new TradeAppVo();
					Integer num1 = mapDay.get(hour);
					appVo.setRequestDate(String.valueOf(hour) + ":00");
					appVo.setRequestNum(num1);
					dataList.add(appVo);
				}
				break;
			case "week": //下一个case也执行
				flag = "week";
				break;
			case "month":
				List<String> list = new LinkedList<>();
				int len = 0;
				if (flag.equals("week")) {
					list = DateUtils.getWeekEveryDays(nowDate);
					len = list.size();
				} else {
					list = DateUtils.getMonthEveryDays(nowDate);
					len = list.size();
				}
				gatewayLogDayVO.setBeginDate(list.get(0));
				gatewayLogDayVO.setEndDate(list.get(list.size() - 1));
				gatewayLogDayVO.setOpcAppCode(appCode);
				appList = gatewayLogDayService.selectCountByDate(gatewayLogDayVO);
				Map<String, Integer> mapWeek = new LinkedHashMap<String, Integer>(); // 返回
				for (int i = 0; i < len; i++) {
					mapWeek.put(list.get(i), 0);
				}
				for (String key : mapWeek.keySet()) {
					TradeAppVo appVo = new TradeAppVo();
					appVo.setRequestDate(key);
					appVo.setRequestNum(0);
					if (appList != null && appList.size() > 0) {
						for (TradeAppVo data : appList) {
							if (key.equals(data.getRequestDate())) {
								appVo.setRequestNum(data.getRequestNum());
								break;
							}
						}
					}
					dataList.add(appVo);
				}
				break;
			case "year":
				String beginDate = nowDate.substring(0, 4) + "0101";
				String endDate = nowDate.substring(0, 4) + "1231";
				gatewayLogDayVO.setBeginDate(beginDate);
				gatewayLogDayVO.setEndDate(endDate);
				gatewayLogDayVO.setOpcAppCode(appCode);
				appList = gatewayLogDayService.selectCountByYear(gatewayLogDayVO);
				Map<String, Integer> mapYear = new LinkedHashMap<String, Integer>(); // 返回
				for (int i = 1; i <= 12; i++) {
					mapYear.put(String.valueOf(i), 0);
				}
				for (String key : mapYear.keySet()) {
					TradeAppVo appVo = new TradeAppVo();
					appVo.setRequestDate(key);
					appVo.setRequestNum(0);
					if (appList != null && appList.size() > 0) {
						for (TradeAppVo app : appList) {
							app.setRequestDate(String.valueOf(Integer.parseInt(app.getRequestDate())));
							if (key.equals(app.getRequestDate())) {
								appVo.setRequestNum(app.getRequestNum());
								break;
							}
						}
					}
					dataList.add(appVo);
				}
				break;
			default:
				break;
		}
		// 整理给前台返回格式
		List<TradeAppVo> logList = new ArrayList<>();
		if (dataList != null && dataList.size() > 0) {
			for (TradeAppVo data : dataList) {
				TradeAppVo gate = new TradeAppVo();
				gate.setRequestDate(data.getRequestDate());
				gate.setRequestNum(data.getRequestNum());
				logList.add(gate);
			}
		}
//		统计
//		logList

		//异常
		int gateNum = gatewayLogService.selectGateCount(gatewayLog);
		int busNum = gatewayLogService.selectBusCount(gatewayLog);
		int infoNum = gatewayLogService.selectInfoCount(gatewayLog);
		int gateNums = (gateNum == 0) ? 1 : gateNum;
		int busNums = (busNum == 0) ? 1 : busNum;
		int infoNums = (infoNum == 0) ? 1 : infoNum;
		//异常总数
		int sumCount = gateNums + busNums + infoNums;

//		数据 hashMap
//		统计 logList
//		异常 hashMap1
//		接口列表  pages.getRecords()

		String rest = "";

		rest = rest + "服务总数:" + hashMap.get("apiCount") + "个，执行次数:" + hashMap.get("callCount") + "个。\r\n" +
				"成功数:" + hashMap.get("successCount") + "次，失败数:" + hashMap.get("failCount") + "次。\r\n" +
				"业务异常:" + hashMap.get("busCount") + "个，网关异常数:" + hashMap.get("gateCount") + "个，通讯异常数:" + hashMap.get("infoCount") + "个。\r\n" +
				"成功率:" + successRate + "%。\r\n\r\n\r\n";
		switch (type) {
			case "day":
				rest = rest + "本日调用趋势\r\n\r\n";
				break;
			case "week":
				rest = rest + "本周调用趋势\r\n\r\n";
				break;
			case "month":
				rest = rest + "本月调用趋势\r\n\r\n";
				break;
			case "year":
				rest = rest + "本年调用趋势\r\n\r\n";
				break;
		}
		for (TradeAppVo tradeAppVo : logList) {
			rest = rest + "时间:" + tradeAppVo.getRequestDate() + ",交易总数:" + tradeAppVo.getRequestNum() + "。\r\n";
		}
		rest = rest + "\r\n\r\n";
		NumberFormat numberFormat = NumberFormat.getInstance();
		numberFormat.setMaximumFractionDigits(2);

		rest = rest + "异常相应占比\r\n\r\n";
		rest = rest + "业务异常：" + numberFormat.format((float) busNums / (float) sumCount * 100) + "%,网关异常：" + numberFormat.format((float) gateNums / (float) sumCount * 100) + "%,通讯异常：" + numberFormat.format((float) infoNums / (float) sumCount * 100) + "%。\r\n\r\n\r\n";

		rest = rest +"接口列表\r\n\r\n";
		int apinum = 1;
		for (ApiVO apiVO : pages.getRecords()) {
			rest = rest + "序号：" + (apinum++) + ",  接口名称：" + apiVO.getApiName() + ",  接口编号：" + apiVO.getApiCode() + ",  版本：" + apiVO.getApiVersion()
					+ ",  访问协议：" + apiVO.getAccessProtocol() + ",  路径：" + apiVO.getApiPath() + ",  安全认证类型：" + apiVO.getSafeType() + ",  报文类型："
					+ apiVO.getMessageType() + ",  权限等级：" + apiVO.getPrivilegeLevel() + ",  是否收费：" + apiVO.getIsCost() + "。\r\n";
		}

		return R.data(rest);
	}

}
